package com.turing.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.turing.merchant.entity.CustomerGood;
import com.turing.merchant.entity.Good;
import com.turing.merchant.entity.Merchant;
import com.turing.merchant.entity.MerchantCustomer;
import com.turing.merchant.feign.*;
import com.turing.merchant.mapper.CustomerGoodMapper;
import com.turing.merchant.mapper.MerchantCustomerMapper;
import com.turing.merchant.mapper.MerchantMapper;
import com.turing.merchant.mapper.GoodMapper;
import com.turing.merchant.service.GoodService;
import enums.ErrorCode;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import result.Result;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Target;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author 28123
 * @description 针对表【good(商品)】的数据库操作Service实现
 * @createDate 2023-05-09 20:31:20
 */
@Service
public class GoodServiceImpl extends ServiceImpl<GoodMapper, Good>
        implements GoodService {

    @Resource
    private HttpServletRequest request;
    @Resource
    private AuthService authService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private CustomerWithdrawalsService customerWithdrawalsService;
    @Resource
    private CustomerGoodMapper customerGoodMapper;
    @Resource
    private CustomerService customerService;
    @Resource
    private MerchantMapper merchantMapper;
    @Resource
    private MissionService missionService;
    @Resource
    private MerchantCustomerMapper merchantCustomerMapper;

    @Override
    public Result geGoodById(String id) {
        Map map = baseMapper.geGoodById(id);
        if (map == null) {
            return Result.fail(ErrorCode.NODATA);
        }
        return Result.success(map);
    }

    @Override
    public Result myGoodList(String merchantId, String gdId, Integer cgState, String gdCreateTime, Integer pageNum, Integer pageSize) {
        //获取token
        String token = request.getHeader("Authorization");
        String tokenHead = "Bearer ";
        token = token.substring(tokenHead.length());
        //根据token获取id
        Result infoByToken = authService.getUserInfoByToken(token);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(infoByToken.getData()));
        String username = jsonObject.getString("username");
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<Map> list = baseMapper.myGoodList(merchantId, gdId, cgState, gdCreateTime, pageNum, pageSize, username);
        if (list.size() == 0) {
            return Result.fail(ErrorCode.NODATA);
        }
        if (pageNum != null && pageSize != null) {
            return Result.success(new PageInfo<>(list));
        }
        return Result.success(list);
    }

    @Override
    public Result goodList(String merchantName, String gdName, Integer priceType, Integer gdState, Integer pageNum, Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<Map> list = baseMapper.goodList(merchantName, gdName, priceType, gdState, pageNum, pageSize);
        if (list.size() == 0) {
            return Result.fail(ErrorCode.NODATA);
        }
        if (pageNum != null && pageSize != null) {
            return Result.success(new PageInfo<>(list));
        }
        return Result.success(list);
    }

    @Override
    public boolean checkGdName(String gdName, String merchantId, String gdId) {
        LambdaQueryWrapper<Good> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Good::getMerchantId, merchantId)
                .eq(Good::getGdName, gdName).eq(gdId != null, Good::getGdId, gdId);
        List<Good> goods = baseMapper.selectList(wrapper);
        return goods.size() == 0 ? true : false;
    }

    @Override
    public Result deleteByIds(String[] ids) {
        List<String> oneList = new ArrayList<>();
        for (String id : ids) {
            //关联了正在进行中,赏金大于0的任务 不能删
            List<Map> map = baseMapper.selectByMission(id);
            if (map == null) {
                oneList.add(id);
            }
        }
        //遍历得到每一条商品的id
        for (String id : oneList) {
            //需要加分布式锁,防止删除同时用户购买或使用商品
            // 加锁 锁id
            ValueOperations stringOps = redisTemplate.opsForValue();
            Long now = System.currentTimeMillis();
            while (System.currentTimeMillis() < (now + 5000)) {
                if (stringOps.setIfAbsent("gdId::" + id, 1, 3, TimeUnit.SECONDS)) {
                    baseMapper.deleteById(id);
                    redisTemplate.delete("gdId::" + id);
                    break;
                }
            }
        }
        //用户未消费的商品需要退款，退款时商品金额要从购买商品时的流水中获取
        for (String gdId : oneList) {
            LambdaQueryWrapper<CustomerGood> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CustomerGood::getGdId, gdId)
                    .eq(CustomerGood::getCgState, 0);
            CustomerGood customerGood = customerGoodMapper.selectOne(wrapper);
            if (customerGood != null) {
                //用户未消费的商品需要退款，退款时商品金额要从购买商品时的流水中获取
                JSONObject cwListForPc = JSON.parseObject(JSON.toJSONString(customerWithdrawalsService.cwListForPc(customerGood.getCusId(), customerGood.getGdId(), null, null, null)));
                Double kwValue = cwListForPc.getDouble("kwValue");
                //退款后，用户商品中，对应的未消费商品数量要设置为0
                customerGood.setGdCount(0);
                //退款后，用户商品中，增加退货记录
                LambdaQueryWrapper<CustomerGood> wrapper1 = new LambdaQueryWrapper<>();
                wrapper.eq(CustomerGood::getGdId, gdId)
                        .eq(CustomerGood::getCgState, 2);
                CustomerGood customerGood1 = customerGoodMapper.selectOne(wrapper1);
                customerGood1.setCgId(UUID.randomUUID().toString());
                customerGood1.setCusId(customerGood.getCusId());
                customerGood1.setGdId(gdId);
                customerGood1.setGdCount(customerGood.getGdCount());
                customerGood1.setCgCreateTime(new Date());
                customerGood1.setGdAmount(BigDecimal.valueOf(kwValue));
                customerGood1.setPriceType(1);
                customerGoodMapper.insert(customerGood1);
                //得到用户
//                Result result = customerService.cusListByCusIds(ids);
//                JSONObject cusListByCusIds = (JSONObject) JSON.parse(JSON.toJSONString(result.getData()));
//                //退款后，修改用户余额
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("cusId", cusListByCusIds.getString("cusId"));
//                jsonObject.put("cusAmount", cusListByCusIds.getString("cusAmount"));
//                customerService.cusEdit(jsonObject);
//                //退款后，增加客户流水，cwInfo为”商品退款”，sourceId为null，targetId为用户主键
//                JSONObject jsonObject2 = new JSONObject();
//                jsonObject2.put("cwId", UUID.randomUUID().toString());
//                jsonObject2.put("cwInfo", "商品退款");
//                jsonObject2.put("targetId", customerGood.getCusId());
//                jsonObject2.put("sourceId", null);
//                if (customerGood.getPriceType() == 0) {
//                    jsonObject2.put("targetReValue", cusListByCusIds.getDouble("cusAmount"));
//                } else {
//                    jsonObject2.put("targetReValue", cusListByCusIds.getDouble("kgCoin"));
//                }
//                jsonObject2.put("cwCreateTime", new Date());
//                if (customerGood.getPriceType() == 0) {
//                    jsonObject2.put("cwType", 0);
//                } else {
//                    jsonObject2.put("cwType", 1);
//                }
//                jsonObject2.put("cwValue", kwValue);
//                customerWithdrawalsService.cwAddSave(jsonObject2);
//                //退款后，给用户发送站内信
//                Good good = baseMapper.selectById(gdId);
//                JSONObject jsonObject1 = new JSONObject();
//                jsonObject1.put("messageId", UUID.randomUUID().toString());
//                jsonObject1.put("messageTitle", "商品退款通知");
//                jsonObject1.put("messageContent", "您购买的" + good.getGdName() + "商品,退款成功,共退" + good.getGdCount() + "个,价值" + good.getGdCount() * good.getGdPrice().doubleValue() + "元");
//                jsonObject1.put("customerIds", customerGood.getCusId());
//                jsonObject1.put("startTime", new Date());
//                jsonObject1.put("endTime", new Date());
//                jsonObject1.put("messageState", 0);
//                jsonObject1.put("messageType", 0);
//                customerWithdrawalsService.addSave(jsonObject1);
            }
        }


        return Result.success();
    }

    @Override
    public Result downShelf(JSONObject jsonObject) {
        String token1 = request.getHeader("Authorization");
        JSONArray id = jsonObject.getJSONArray("id");
        List<String> oneList = new ArrayList<>();
        for (Object id1 : id) {
            //关联了正在进行中,赏金大于0的任务 不能下架
            List<Map> map = baseMapper.selectByMission(id1.toString());
            if (map != null) {
                oneList.add(id1.toString());
            }
        }
        //遍历得到每一条商品的id
        for (String id1 : oneList) {
            //需要加分布式锁,防止下架同时用户购买或使用商品
            // 加锁 锁id
            ValueOperations stringOps = redisTemplate.opsForValue();
            Long now = System.currentTimeMillis();
            Good good = baseMapper.selectById(id1);
            while (System.currentTimeMillis() < (now + 5000)) {
                if (stringOps.setIfAbsent("gdId::" + id1, 1, 3, TimeUnit.SECONDS)) {
                    good.setGdState(1);
                    baseMapper.updateById(good);
                    redisTemplate.delete("gdId::" + id1);
                    break;
                }
            }
        }
        //用户未消费的商品需要退款，退款时商品金额要从购买商品时的流水中获取
        for (String gdId : oneList) {
            LambdaQueryWrapper<CustomerGood> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CustomerGood::getGdId, gdId)
                    .eq(CustomerGood::getCgState, 0);
            List<CustomerGood> customerGoods = customerGoodMapper.selectList(wrapper);
            if (customerGoods != null) {
                List<String> list = new ArrayList<>();
                Double cwValue = 0.0;
                for (CustomerGood customerGood : customerGoods) {
                    //退款后，用户商品中，对应的未消费商品数量要设置为0
                    customerGood.getGdId();
                    customerGood.setGdCount(0);
                    customerGoodMapper.updateById(customerGood);
                    //用户未消费的商品需要退款，退款时商品金额要从购买商品时的流水中获取
                    Result result = customerWithdrawalsService.cwListForPc(customerGood.getCusId(), gdId, null, null, null);
                    JSONArray jsonObject3 = JSONArray.parseArray(JSON.toJSONString(result.getData()));

                    for (Object o : jsonObject3) {
                        Map m = (Map) o;
                        cwValue += Double.parseDouble(m.get("cwValue").toString());
                    }
                    //退款后，用户商品中，增加退货记录
                    customerGood.setCgId(UUID.randomUUID().toString());
                    customerGood.setCusId(customerGood.getCusId());
                    customerGood.setGdId(gdId);
                    customerGood.setGdCount(customerGood.getGdCount());
                    customerGood.setCgState(2);
                    customerGood.setCgCreateTime(new Date());
                    customerGood.setGdAmount(BigDecimal.valueOf(cwValue));
                    if (customerGood.getPriceType() == 0) {
                        customerGood.setPriceType(0);
                    } else {
                        customerGood.setPriceType(1);
                    }
                    customerGoodMapper.insert(customerGood);
                    //得到用户
                    list.add(customerGood.getCusId());
                }
                String[] ids =list.toArray(new String[list.size()]);
                System.out.println("ids = " + ids);
                Result result1 = customerService.cusListByCusIds(token1,ids);
                JSONArray cusListByCusIds = JSONArray.parseArray(JSON.toJSONString(result1.getData()));
                String id1 = "";
                Double target1 = 0.0;
                for (Object o : cusListByCusIds) {
                    Map m = (Map) o;
                    id1 += m.get("cusId").toString();
                  //  target1 += m.get("").toString();
                }
                //退款后，修改用户余额
                JSONObject jsonObject6 = new JSONObject();
                jsonObject6.put("cusId", id1);
                jsonObject6.put("cusAmount", cwValue);
                customerService.cusEdit(jsonObject6);
                //退款后，增加客户流水，cwInfo为”商品退款”，sourceId为null，targetId为用户主键
                for (CustomerGood customerGood : customerGoods) {
                    JSONObject jsonObject2 = new JSONObject();
                    jsonObject2.put("cwId", UUID.randomUUID().toString());
                    jsonObject2.put("cwInfo", "商品退款");
                    jsonObject2.put("targetId", id1);
                    jsonObject2.put("sourceId", null);
                    if (customerGood.getPriceType() == 0) {
                       // jsonObject2.put("targetReValue",);
                    } else {
                      //  jsonObject2.put("targetReValue", cusListByCusIds.getDouble("kgCoin"));
                    }
                    jsonObject2.put("cwCreateTime", new Date());
                    if (customerGood.getPriceType() == 0) {
                        jsonObject2.put("cwType", 0);
                    } else {
                        jsonObject2.put("cwType", 1);
                    }
                    jsonObject2.put("cwValue", cwValue);
                    customerWithdrawalsService.cwAddSave(jsonObject2);
                }

//                //退款后，给用户发送站内信
//                Good good = baseMapper.selectById(gdId);
//                JSONObject jsonObject1 = new JSONObject();
//                jsonObject1.put("messageId", UUID.randomUUID().toString());
//                jsonObject1.put("messageTitle", "商品退款通知");
//                jsonObject1.put("messageContent", "您购买的" + good.getGdName() + "商品,退款成功,共退" + good.getGdCount() + "个,价值" + good.getGdCount() * good.getGdPrice().doubleValue() + "元");
//                jsonObject1.put("customerIds", customerGood.getCusId());
//                jsonObject1.put("startTime", new Date());
//                jsonObject1.put("endTime", new Date());
//                jsonObject1.put("messageState", 0);
//                jsonObject1.put("messageType", 0);
//                customerWithdrawalsService.addSave(jsonObject1);
            }
        }
        return Result.success();
    }

    @Override
    public Result goodListByIds(String[] ids) {
        List<Map> list = baseMapper.goodListByIds(ids);
        if (list.size() == 0) {
            return Result.fail(ErrorCode.NODATA);
        }
        return Result.success(list);
    }

    @Override
    public Result goodListForPhone(String categoryId, Integer cdType, String longitude, String latitude, Integer orderType, Integer cityId, String orderState, Integer pageNum, Integer pageSize) {
        //获取token
        String token = request.getHeader("Authorization");
        String tokenHead = "Bearer ";
        token = token.substring(tokenHead.length());
        //根据token获取id
        Result infoByToken = authService.getUserInfoByToken(token);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(infoByToken.getData()));
        System.out.println("jsonObject = " + jsonObject);
        String cusId = jsonObject.getString("username");
        System.out.println("cusId = " + cusId);

        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<Map> list = baseMapper.goodListForPhone(categoryId, cdType, longitude, latitude, orderType, cityId, orderState, pageNum, pageSize, cusId);
        if (list.size() == 0) {
            return Result.fail(ErrorCode.NODATA);
        }
        if (pageNum != null && pageSize != null) {
            return Result.success(new PageInfo<>(list));
        }
        return Result.success(list);
    }

    @Override
    public Result goodEdit(JSONObject jsonObject) {
        Good good = jsonObject.toJavaObject(jsonObject, Good.class);
        ValueOperations stringOps = redisTemplate.opsForValue();
        Long now = System.currentTimeMillis();
        while (System.currentTimeMillis() < (now + 5000)) {
            if (stringOps.setIfAbsent("gdId::" + good.getGdId(), 1, 3, TimeUnit.SECONDS)) {
                baseMapper.updateById(good);
                break;
            }
        }
        return Result.success();
    }

    @Override
    public Result buyGood(JSONObject jsonObject) throws ParseException {
        //获取token
        String token1 = request.getHeader("Authorization");
        String tokenHead = "Bearer ";
        String token = token1.substring(tokenHead.length());
        //根据token获取id
        Result infoByToken = authService.getUserInfoByToken(token);
        JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(infoByToken.getData()));
        String cusId = jsonObject1.getString("username");
        String gdId = jsonObject.getString("gdId");
        Integer gdNum = jsonObject.getInteger("gdNum");
        //查询商品数量
        Good good = baseMapper.selectById(gdId);
        if (good.getGdLeft() < gdNum) {
            return Result.fail(0, "商品数量不足");
        }
        //商品状态是上架才可以买
        if (good.getGdState() != 0){
            return Result.fail(0,"商品不能被购买");
        }
        //验证用户余额或货币是否足够
        JSONObject customerKgCoin = JSON.parseObject(JSON.toJSONString(customerService.geCusById(cusId).getData()));
        if (customerKgCoin.getInteger("kgCoin") < good.getGdPrice().doubleValue() * gdNum || customerKgCoin.getDouble("cusAmount") < good.getGdPrice().doubleValue() * gdNum) {
            return Result.fail(0, "客币或余额不足");
        }
        //购买前验证用户累计购买数量是否超过商品的购买上限
        //Integer integer = customerGoodMapper.selectByGdIdCount(cusId, gdId);
        Integer integer = baseMapper.selectByGdIdCount(cusId, gdId);
        System.out.println("good = " + good.getGdMax());
        System.out.println("integer = " + integer);
        if (integer != null && integer > good.getGdMax()) {
            return Result.fail(0, "超过购买上限");
        }
        ValueOperations stringOps = redisTemplate.opsForValue();
        Long now = System.currentTimeMillis();
        while (System.currentTimeMillis() < (now + 5000)) {
            if (stringOps.setIfAbsent("gdId::" + gdId, 1, 3, TimeUnit.SECONDS)) {
                //修改客户余额或客币
                JSONObject upCustomer = new JSONObject();
                upCustomer.put("cusId", cusId);
                if (good.getPriceType() == 0) {
                    upCustomer.put("cusAmount", customerKgCoin.getDouble("cusAmount") - good.getGdPrice().doubleValue() * gdNum);
                } else {
                    upCustomer.put("kgCoin", customerKgCoin.getDouble("kgCoin") - good.getGdPrice().doubleValue() * gdNum);
                }
                customerService.cusEdit(upCustomer);
                //改变库存
                good.setGdId(gdId);
                good.setGdLeft(good.getGdLeft() - gdNum);
                baseMapper.updateById(good);
                redisTemplate.delete("gdId::" + gdId);
                break;
            }
        }
        //增加用户购买商品记录
        CustomerGood customerGood1 = new CustomerGood();
        customerGood1.setCgId(UUID.randomUUID().toString());
        customerGood1.setCusId(cusId);
        customerGood1.setGdId(gdId);
        customerGood1.setGdCount(gdNum);
        customerGood1.setCgState(0);
        customerGood1.setCgCreateTime(new Date());
        customerGood1.setGdAmount(BigDecimal.valueOf(good.getGdPrice().doubleValue() * gdNum));
        if (good.getPriceType() == 0) {
            customerGood1.setPriceType(0);
        } else {
            customerGood1.setPriceType(1);
        }
        customerGood1.setWxNo(null);
        customerGood1.setOutTradeNo(null);
        customerGoodMapper.insert(customerGood1);
        //增加客户流水
        Merchant merchant = merchantMapper.selectById(good.getMerchantId());
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("cwInfo", "购买商品消费(" + merchant.getMerchantName() + "," + good.getGdName() + "):" + good.getGdPrice() + ":" + gdNum + ":" + good.getCommonPrice());
        jsonObject2.put("targetId", gdId);
        if (good.getPriceType() == 0) {
            jsonObject2.put("sourceReValue", customerKgCoin.getInteger("cusAmount"));
        } else {
            jsonObject2.put("sourceReValue", customerKgCoin.getInteger("kgCoin"));
        }

        jsonObject2.put("targetReValue", good.getGdPrice());
        jsonObject2.put("sourceId", cusId);
        jsonObject2.put("cwCreateTime", new Date());
        if (good.getPriceType() == 0) {
            jsonObject2.put("cwType", 0);
        } else {
            jsonObject2.put("cwType", 1);
        }
        jsonObject2.put("cwvalue", good.getGdPrice().doubleValue() * gdNum);
        customerWithdrawalsService.cwAddSave(jsonObject2);
        //购买商品所关联的正在进行的任务，若用户没领取，需要自动领取任务
        Result result = missionService.miList(token1, null, null, null, null, null, null, good.getMerchantId(), null, null, null, 0, null);
        JSONArray mission = JSONArray.parseArray(JSON.toJSONString(result.getData()));
        for (Object o : mission) {
            System.out.println("111");
            Map m = (Map) o;
            List<Map> map1 = baseMapper.selectDate(gdId);
            Result result1 = missionService.myMissionList(token1, null, m.get("missionId").toString(), 0, 0, null, null);
            JSONArray objects = JSONArray.parseArray(JSON.toJSONString(result1.getData()));
            if (!objects.contains(map1) && !map1.isEmpty()) {
                System.out.println("222");
                JSONObject jsonObject3 = new JSONObject();
                jsonObject3.put("mmsiId", UUID.randomUUID().toString());
                jsonObject3.put("missionId", m.get("missionId"));
                jsonObject3.put("cusId", cusId);
                jsonObject3.put("mmisState", "P");
                jsonObject3.put("signState", 0);
                jsonObject3.put("signDate", null);
                System.out.println("jsonObject3 = " + jsonObject3);
                missionService.myMissionSave(token1, jsonObject3);
            }
        }
        return Result.success();
    }

    @Override
    public Result useGood(JSONObject jsonObject) {
        //获取token
        String token = request.getHeader("Authorization");
        String tokenHead = "Bearer ";
        token = token.substring(tokenHead.length());
        //根据token获取id
        Result infoByToken = authService.getUserInfoByToken(token);
        JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(infoByToken.getData()));
        String cusId = jsonObject1.getString("username");
        String gdId = jsonObject.getString("gdId");
        Integer gdNum = jsonObject.getInteger("gdNum");
        String longitude = jsonObject.getString("longitude");
        String latitude = jsonObject.getString("latitude");
        Good good = baseMapper.selectById(gdId);
        //若客户距离商家超过500米，则不让使用
        Double distance = baseMapper.selectDistance(longitude, latitude, good.getMerchantId());
        if (distance > 500) {
            return Result.fail(0, "距离超过500米");
        }
        //按照购买记录时间排序，来使用商品，使用后要改变购买记录中的商品数量
        //得到可以使用的商品
        List<CustomerGood> customerGood = customerGoodMapper.selectUseGood(gdId, cusId);
        for (int i = 0; i < customerGood.size(); i++) {
            Integer gdCount = customerGood.get(i).getGdCount();
            if (gdCount >= gdNum) {
                customerGood.get(i).setGdCount(gdCount - gdNum);
                customerGoodMapper.updateById(customerGood.get(i));
                break;
            } else if (gdCount < gdNum) {
                gdNum = gdNum - customerGood.get(i).getGdCount();
                customerGood.get(i).setGdCount(0);
                customerGoodMapper.updateById(customerGood.get(i));
                System.out.println("gdNum = " + gdNum);
            }
            if (gdCount == 0) {
                return Result.fail(0, "没有可使用的商品");
            }
        }
        //购买记录中要增加商品使用记录
        CustomerGood customerGood1 = new CustomerGood();
        customerGood1.setCusId(UUID.randomUUID().toString());
        customerGood1.setCusId(cusId);
        customerGood1.setGdId(gdId);
        customerGood1.setGdCount(gdNum);
        customerGood1.setCgState(1);
        customerGood1.setCgCreateTime(new Date());
        customerGood1.setGdAmount(BigDecimal.valueOf(good.getGdPrice().doubleValue() * gdNum));
        if (good.getPriceType() == 0) {
            customerGood1.setPriceType(0);
        } else {
            customerGood1.setPriceType(1);
        }
        customerGood1.setWxNo(null);
        customerGood1.setOutTradeNo(null);
        customerGoodMapper.insert(customerGood1);
        //商品使用后需要改变商家余额
        Merchant merchant = merchantMapper.selectById(good.getMerchantId());
        merchant.setMerchantId(good.getMerchantId());
        double v = (good.getGdPrice().doubleValue() * gdNum) + (merchant.getTotalAmount().doubleValue());
        merchant.setTotalAmount(BigDecimal.valueOf(v));
        merchantMapper.updateById(merchant);
        //若平台抽成大于零，商品使用后需要给平台抽成金额(字典表中的”平台账户”)
        //查平台账户
        JSONObject selectDic = JSON.parseObject(JSON.toJSONString(customerWithdrawalsService.getDic("26", "平台账户").getData()));
        //查流水抽成金额
        Result result = customerWithdrawalsService.cwListForPc(cusId, gdId, null, null, null);
        JSONArray jsonObject3 = JSONArray.parseArray(JSON.toJSONString(result.getData()));
        Double cwValue = 0.0;
        for (Object o : jsonObject3) {
            Map m = (Map) o;
            cwValue += Double.parseDouble(m.get("cwValue").toString());
            System.out.println("m = " + m);
            if (good.getCommonPrice().doubleValue() > 0) {
                JSONObject jsonObject4 = new JSONObject();
                jsonObject4.put("dicId", 26);
                jsonObject4.put("dicName", "平台账户");
                jsonObject4.put("dicInfo", Double.parseDouble(selectDic.getString("dicInfo")) + good.getCommonPrice().doubleValue() * gdNum);
                customerWithdrawalsService.editSave(jsonObject4);
                System.out.println("jsonObject4 = " + jsonObject4);
            }
        }
        Result result1 = customerService.geCusById(cusId);
        JSONObject customer = JSON.parseObject(JSON.toJSONString(result1.getData()));
        //增加商家流水
        JSONObject jsonObject6 = new JSONObject();
        jsonObject6.put("kwInfo", "销售商品收入("+customer.getString("cusNickname") + "," + good.getGdName()+")");
        jsonObject6.put("targetId", good.getMerchantId());
        if (good.getPriceType() == 0) {
            jsonObject6.put("kwType", 0);
        } else {
            jsonObject6.put("kwType", 1);
        }
        jsonObject6.put("sourceId", cusId);
        jsonObject6.put("sourceReValue", good.getGdPrice().doubleValue() * gdNum);
        jsonObject6.put("targetReValue", Double.parseDouble(selectDic.getString("dicInfo")));
        jsonObject6.put("kwValue", good.getGdPrice().doubleValue() * gdNum - gdNum * good.getCommonPrice().doubleValue());
        jsonObject6.put("kwCreateTime", new Date());
        customerWithdrawalsService.kwAddSave(jsonObject6);

        //给商家店长及管理员发站内信
        //消息增加
//            Merchant merchant1 = merchantMapper.selectById(good.getMerchantId());
//            System.out.println("merchant1 = " + merchant1);

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("messageId", UUID.randomUUID().toString());
        jsonObject2.put("messageTitle", "购买商品到账");
        if (good.getPriceType() == 0) {
            jsonObject2.put("messageContent", customer.getString("cusNickname") + "在" + merchant.getMerchantName() + "使用了" + gdNum + "个" + good.getGdName() + ", 到账" + (good.getGdPrice().doubleValue() * gdNum - gdNum * good.getCommonPrice().doubleValue()) + 0);
            System.out.println("jsonObject2 = " + jsonObject2);
        } else {
            jsonObject2.put("messageContent", customer.getString("cusNickname") + "在" + merchant.getMerchantName() + "使用了" + gdNum + "个" + good.getGdName() + ", 到账" + (good.getGdPrice().doubleValue() * gdNum - gdNum * good.getCommonPrice().doubleValue()) + 1);
        }
        String shus = merchant.getCusId();
        String[] str = shus.split(",");
        jsonObject2.put("customerIds", Arrays.asList(str));
        System.out.println("店长 = " + Arrays.asList(str));
        jsonObject2.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        jsonObject2.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        jsonObject2.put("messageState", 1);
        jsonObject2.put("messageType", 0);
        System.out.println("jsonObject2 = " + jsonObject2);
        customerWithdrawalsService.addSave(jsonObject2);
        System.out.println("customerWithdrawalsService.addSave(jsonObject2) = " + customerWithdrawalsService.addSave(jsonObject2));

        //若抽成金额大于零，增加平台流水
        JSONObject jsonObject5 = new JSONObject();
        jsonObject5.put("kwId", UUID.randomUUID().toString());
        jsonObject5.put("sourceId", good.getMerchantId());
        jsonObject5.put("targetId", null);
        jsonObject5.put("kwValue", gdNum * good.getCommonPrice().doubleValue());
        if (good.getPriceType() == 0) {
            jsonObject5.put("kwType", 0);
        } else {
            jsonObject5.put("kwType", 1);
        }
        jsonObject5.put("kwInfo", "商品抽成(" + customer.getString("cusNickname") + "用户," + merchant.getMerchantName() + "商家," + good.getGdName() + "商品," + gdNum + "个)");
        jsonObject5.put("sourceReValue", Double.parseDouble(selectDic.getString("dicInfo")));
        jsonObject5.put("kwCreateTime", new Date());
        customerWithdrawalsService.kwAddSave(jsonObject5);
        System.out.println("jsonObject5 = " + jsonObject5);


        return Result.success();
    }
}




